package com.changgou.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 * 用于用户权限鉴别
 */
@Component
public class AuthorizeFilter implements GlobalFilter,Ordered {
    //令牌头名字
    private static final String AUTHORIZE_TOKEN = "Authorization";
    /**
     * 全局拦截
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求的URI
        String path = request.getURI().getPath();

        //如果是登录、goods等开放的微服务[这里的goods部分开放],则直接放行,这里不做完整演示，完整演示需要设计一套权限系统
//        if (path.startsWith("/api/user/login") || path.startsWith("/api/brand/search/")) {
        if (URLFilter.hasAuthorize(path)) {
            //放行
            Mono<Void> filter = chain.filter(exchange);
            return filter;
        }

        //获取用户令牌信息(1.头文件2.参数3.cookie)
        //头文件中
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        //令牌封装到头文件中
        boolean hasToken=true;
        if(StringUtils.isEmpty(token)){
            //所有参数中的第一个
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
            hasToken=false;
        }
        if(StringUtils.isEmpty(token)){
            HttpCookie httpCookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if (httpCookie!=null){
                token=httpCookie.getValue();
            }
        }
        //拦截返回空
        if(StringUtils.isEmpty(token)){
            //返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回空数据
            return response.setComplete();
        }
        //校验令牌
//        try {
            //用到了oauth2,含有证书,不进行校验
//            Claims claims = JwtUtil.parseJWT(token);
//        } catch (Exception e) {
            //无效拦截
            //返回401
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回空数据
//            return response.setComplete();
//        }
        //将令牌封装到头文件中
        if(!hasToken){
            //判断前缀是否正确
            if(!token.startsWith("bearer") && !token.startsWith("Bearer")){
                token="bearer "+token;
            }
            request.mutate().header(AUTHORIZE_TOKEN,token);
        }
        //放行
        return chain.filter(exchange);
    }

    /**
     * 排序,0为第一个
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
